<template>
  <div class="admin-products">
    <div class="page-header">
      <h2>产品管理</h2>
      <div class="header-actions">
        <el-button v-if="hasPermission('product_add')" type="primary" @click="addProduct">
          添加产品
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.keyword" placeholder="搜索产品名称" clearable @input="handleSearch" />
        </el-col>
        <el-col :span="4">
          <el-tree-select
            v-model="searchForm.category"
            :data="treeData"
            check-strictly
            clearable
            :render-after-expand="false"
            placeholder="产品分类"
            @change="handleSearch"
            style="width: 100%"
            :props="{ disabled: 'disabled' }"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.exhibitorId" placeholder="所属展商" clearable @change="handleSearch">
            <el-option v-for="exhibitor in exhibitorList" :key="exhibitor.id" :label="exhibitor.companyName"
              :value="exhibitor.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 产品列表 -->
    <el-table :data="productList" border stripe v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="productName" label="产品名称" min-width="200" />
      <el-table-column prop="productCategory" label="产品分类" min-width="200" />
      <el-table-column prop="priceRange" label="价格区间" width="120" />
      <el-table-column prop="exhibitorName" label="所属展商" min-width="150" />
      <el-table-column prop="isFeatured" label="推荐" width="80">
        <template #default="{ row }">
          <el-tag :type="row.isFeatured ? 'success' : 'info'">
            {{ row.isFeatured ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
            {{ row.status === 'active' ? '正常' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="{ row }">
          <el-button v-if="hasPermission('product_edit')" type="primary" size="small" @click="editProduct(row)">
            编辑
          </el-button>
          <el-button type="success" size="small" @click="toggleFeatured(row)">
            {{ row.isFeatured ? '取消推荐' : '设为推荐' }}
          </el-button>
          <el-button v-if="hasPermission('product_delete')" type="danger" size="small" @click="deleteProduct(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加/编辑产品对话框 -->
    <el-dialog v-model="showAddDialog" :title="editingProduct ? '编辑产品' : '添加产品'" width="600px">
      <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="100px">
        <el-form-item label="所属展商" prop="exhibitorId">
          <el-select filterable v-model="productForm.exhibitorId" placeholder="请选择展商" style="width: 100%">
            <el-option v-for="exhibitor in exhibitorList" :key="exhibitor.id" :label="exhibitor.companyName"
              :value="exhibitor.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品分类" prop="productCategory">
          <el-tree-select
            v-model="productForm.productCategory"
            :data="treeData"
            check-strictly
            :render-after-expand="false"
            placeholder="请选择产品分类"
            style="width: 100%"
            :props="{ disabled: 'disabled' }"
          />
        </el-form-item>
        <el-form-item label="产品描述" prop="productDescription">
          <rich-text-editor v-model="productForm.productDescription" placeholder="请输入产品描述（可包含技术规格等信息）" />
        </el-form-item>
        <el-form-item label="价格区间" prop="priceRange">
          <el-input v-model="productForm.priceRange" placeholder="请输入价格区间，如：80-120万" />
        </el-form-item>
        <el-form-item label="产品图片" prop="productImage">
          <div class="image-upload-container">
            <el-upload class="image-uploader" :action="uploadAction" :headers="uploadHeaders"
              :data="{ type: 'product' }" :show-file-list="false"
              :on-success="(response) => handleImageSuccess(response)" :before-upload="beforeImageUpload"
              accept="image/*">
              <img v-if="productForm.productImage" :src="productForm.productImage" class="uploaded-image" />
              <el-icon v-else class="image-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <el-input v-model="productForm.productImage" placeholder="或直接输入图片URL" style="margin-top: 10px;" />
          </div>
        </el-form-item>
        <el-form-item label="推荐产品">
          <el-switch v-model="productForm.isFeatured" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="productForm.status">
            <el-option label="正常" value="active" />
            <el-option label="下架" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveProduct" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { exhibitorProductApi, exhibitorApi } from '@/api/admin'
import config from '@/config'

import RichTextEditor from '@/components/RichTextEditor.vue'

export default {
  name: 'AdminProducts',
  components: {
    Plus,
    RichTextEditor
  },
  setup() {

    const treeData = [
      {
        label: '基础设施',
        value: '基础设施',
        disabled: true,
        children: [
          { label: '算力（算力中心、AI加速卡）', value: '基础设施-算力' },
          { label: '算法（大模型训练算法）', value: '基础设施-算法' },
          { label: '数据（具身数据中心、验证仿真中心、大型组件库等）', value: '基础设施-数据' }
        ]
      },
      {
        label: '上游-软件及硬件组件',
        value: '上游-软件及硬件组件',
        disabled: true,
        children: [
          {
            label: '感知系统',
            value: '上游-感知系统',
            children: [
              { label: '视觉模块', value: '感知-视觉模块' },
              { label: '力觉模块', value: '感知-力觉模块' },
              { label: '交互模块', value: '感知-交互模块' },
              { label: '算法模块', value: '感知-算法模块' },
              { label: '惯导IMU', value: '感知-惯导IMU' },
              { label: '嗅觉传感器', value: '感知-嗅觉传感器' }
            ]
          },
          {
            label: '认知系统',
            value: '上游-认知系统',
            children: [
              { label: '大模型', value: '认知-大模型' },
              { label: 'AI芯片', value: '认知-AI芯片' }
            ]
          },
          {
            label: '执行系统',
            value: '上游-执行系统',
            children: [
              { label: '控制系统', value: '执行-控制系统' },
              { label: '伺服系统（电机、编码器等）', value: '执行-伺服系统' },
              { label: '传动系统（减速器、轴承、丝杠、电控板等）', value: '执行-传动系统' },
              { label: '动力系统（电源、动力能源等）', value: '执行-动力系统' }
            ]
          },
          {
            label: '系统平台',
            value: '上游-系统平台',
            children: [
              { label: '操作系统', value: '平台-操作系统' },
              { label: '硬件抽象', value: '平台-硬件抽象' },
              { label: '通信框架', value: '平台-通信框架' }
            ]
          },
          { label: '工具链（基础开发框架与软件栈、AI模型训练与优化套件等）', value: '上游-工具链' },
          { label: '中间件（通信与数据流管理、仿真与数字孪生服务等）', value: '上游-中间件' },
          { label: '其他组件（元器件、线束线缆、云服务、物联网相关组件、通信模组等）', value: '上游-其他组件' }
        ]
      },
      {
        label: '中游-整机设计、研发、系统集成',
        value: '中游-整机设计研发系统集成',
        disabled: true,
        children: [
          { label: '人形、类人形', value: '中游-人形类人形' },
          {
            label: '工业机械手',
            value: '中游-工业机械手',
            children: [
              { label: '六轴', value: '机械手-六轴' },
              { label: 'SCARA', value: '机械手-SCARA' },
              { label: '直线模组', value: '机械手-直线模组' },
              { label: '并联', value: '机械手-并联' },
              { label: '重载', value: '机械手-重载' }
            ]
          },
          {
            label: '移动机器人',
            value: '中游-移动机器人',
            children: [
              { label: 'AGV', value: '移动-AGV' },
              { label: 'AMR', value: '移动-AMR' },
              { label: '无人叉车', value: '移动-无人叉车' },
              { label: '重载移动', value: '移动-重载' }
            ]
          },
          { label: '协作机器人', value: '中游-协作机器人' },
          {
            label: '商用服务机器人',
            value: '中游-商用服务机器人',
            children: [
              { label: '送餐机器人', value: '商服-送餐机器人' },
              { label: '配送机器人', value: '商服-配送机器人' },
              { label: '清洁机器人（室内）', value: '商服-清洁室内' },
              { label: '清洁机器人（室外）', value: '商服-清洁室外' }
            ]
          },
          {
            label: '医用机器人',
            value: '中游-医用机器人',
            children: [
              { label: '手术机器人', value: '医用-手术机器人' },
              { label: '康复机器人', value: '医用-康复机器人' },
              { label: '理疗机器人', value: '医用-理疗机器人' }
            ]
          },
          { label: '教育机器人', value: '中游-教育机器人' },
          { label: '四足机器人', value: '中游-四足机器人' },
          { label: '双足机器人', value: '中游-双足机器人' },
          { label: '灵巧手', value: '中游-灵巧手' },
          { label: '陪伴类机器人', value: '中游-陪伴类机器人' },
          { label: '水下机器人', value: '中游-水下机器人' },
          { label: '特种机器人', value: '中游-特种机器人' },
          { label: '其他类型机器人', value: '中游-其他类型' }
        ]
      },
      {
        label: '下游',
        value: '下游',
        disabled: true,
        children: [
          { label: '制造业', value: '下游-制造业' },
          { label: '农业', value: '下游-农业' },
          { label: '建筑', value: '下游-建筑' },
          { label: '能源', value: '下游-能源' },
          { label: '商贸物流', value: '下游-商贸物流' },
          { label: '医疗健康', value: '下游-医疗健康' },
          { label: '教育', value: '下游-教育' },
          { label: '商业社区服务', value: '下游-商业社区服务' },
          { label: '安全应急和极限环境作业', value: '下游-安全应急' },
          { label: '其他应用场景', value: '下游-其他应用' }
        ]
      },
      {
        label: '产业链配套',
        value: '产业链配套',
        disabled: true,
        children: [
          { label: '工业设计', value: '配套-工业设计' },
          { label: '代工', value: '配套-代工' },
          { label: '机器人检测、维修、测试验证等', value: '配套-检测维修测试' },
          { label: '其他配套服务', value: '配套-其他服务' }
        ]
      }
    ];

    const loading = ref(false)
    const saving = ref(false)
    const showAddDialog = ref(false)
    const editingProduct = ref(null)
    const productList = ref([])
    const exhibitorList = ref([])

    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      category: '',
      exhibitorId: null
    })

    // 产品表单
    const productForm = reactive({
      exhibitorId: null,
      productName: '',
      productCategory: '',
      productDescription: '',
      priceRange: '',
      productImage: '',
      isFeatured: false,
      status: 'active'
    })

    // 表单验证规则
    const productRules = {
      exhibitorId: [{ required: true, message: '请选择展商', trigger: 'change' }],
      productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
      productCategory: [{ required: true, message: '请选择产品分类', trigger: 'change' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }

    // 分页
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 图片上传配置
    const apiConfig = config.getApiConfig()
    const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`)
    const uploadHeaders = ref({
      'token': localStorage.getItem('adminToken') || ''
    })

    // 权限检查
    const hasPermission = (permission) => {
      // 这里应该根据实际权限系统实现
      return true
    }

    // 加载产品列表
    const loadProducts = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        }
        // 这里需要调用新的产品管理API，支持跨展商查询
        const response = await exhibitorProductApi.getProductPage(null, params)
        if (response.success) {
          productList.value = response.data.records
          pagination.total = response.data.total
        } else {
          ElMessage.error(response.msg || '加载产品列表失败')
        }
      } catch (error) {
        console.error('加载产品列表失败:', error)
        ElMessage.error('加载产品列表失败')
      } finally {
        loading.value = false
      }
    }

    // 加载展商列表
    const loadExhibitors = async () => {
      try {
        const response = await exhibitorApi.getExhibitorPage({
          page: 1,
          size: 1000,
          status: 'approved' // 只获取已审核通过的展商
        })
        if (response.success) {
          exhibitorList.value = response.data.records
        }
      } catch (error) {
        console.error('加载展商列表失败:', error)
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadProducts()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = ''
      searchForm.category = ''
      searchForm.exhibitorId = null
      handleSearch()
    }

    // 添加产品
    const addProduct = () => {
      editingProduct.value = null
      Object.assign(productForm, {
        exhibitorId: null,
        productName: '',
        productCategory: '',
        productDescription: '',
        priceRange: '',
        productImage: '',
        isFeatured: false,
        status: 'active'
      })
      showAddDialog.value = true
    }

    // 编辑产品
    const editProduct = (product) => {
      editingProduct.value = product
      Object.assign(productForm, product)
      showAddDialog.value = true
    }

    // 保存产品
    const saveProduct = async () => {
      try {
        saving.value = true

        let response
        if (editingProduct.value) {
          response = await exhibitorProductApi.updateProduct(productForm)
        } else {
          response = await exhibitorProductApi.addProduct(productForm)
        }

        if (response.success) {
          ElMessage.success(editingProduct.value ? '更新产品成功' : '添加产品成功')
          showAddDialog.value = false
          loadProducts()
        } else {
          ElMessage.error(response.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存产品失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }

    // 切换推荐状态
    const toggleFeatured = async (product) => {
      try {
        const newFeaturedStatus = !product.isFeatured
        const response = await exhibitorProductApi.updateFeaturedStatus(product.id, newFeaturedStatus)
        if (response.success) {
          product.isFeatured = newFeaturedStatus
          ElMessage.success(newFeaturedStatus ? '设为推荐成功' : '取消推荐成功')
        } else {
          ElMessage.error(response.msg || '操作失败')
        }
      } catch (error) {
        console.error('切换推荐状态失败:', error)
        ElMessage.error('操作失败')
      }
    }

    // 删除产品
    const deleteProduct = async (product) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除产品"${product.productName}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await exhibitorProductApi.deleteProduct(product.id)
        if (response.success) {
          ElMessage.success('删除成功')
          loadProducts()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除产品失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 15

      if (!isImage) {
        ElMessage.error('只能上传图片格式的文件!')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过 15MB!')
        return false
      }
      return true
    }

    // 图片上传成功处理
    const handleImageSuccess = (response) => {
      if (response && (response.code === '200' || response.code === 200)) {
        productForm.productImage = response.data.url
        ElMessage.success('图片上传成功!')
      } else {
        ElMessage.error('图片上传失败!')
      }
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      loadProducts()
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
      loadProducts()
    }

    onMounted(() => {
      loadExhibitors()
      loadProducts()
    })

    return {
      loading,
      saving,
      showAddDialog,
      editingProduct,
      productList,
      exhibitorList,
      searchForm,
      productForm,
      productRules,
      pagination,
      treeData,
      hasPermission,
      loadProducts,
      loadExhibitors,
      handleSearch,
      resetSearch,
      addProduct,
      editProduct,
      saveProduct,
      toggleFeatured,
      deleteProduct,
      beforeImageUpload,
      handleImageSuccess,
      uploadAction,
      uploadHeaders,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.admin-products {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 图片上传样式 */
.image-upload-container {
  width: 100%;
}

.image-uploader {
  width: 100%;
}

.image-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 100%;
  height: 148px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
</style>
